var MD5 = require('./md5.js');
var Common = require('./common.js');

function POSTJSON(url, data, showloading, msgTitle, complete_callBack) {
    const app = getApp();
    var promise = new Promise((resolve, reject) => {
        setTimeout(function(){
            if (showloading) {
                wx.showLoading({
                    title: '',
                    icon: 'none',                    
                    mask: true
                });
            }
        }, 1);
        wx.request({
            url: url,
            data: data,
            method:"POST",
            header: {
                'content-type': 'application/json'
            },
            complete: function(res) {                
                showloading = false;
                if (complete_callBack){
                    complete_callBack();
                }
            },
            fail: function(val) {
                console.group("%c【%s】- 失败请求服务端：%s\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
                    "background-color:#faa;font-weight:800;", new Date().toLocaleString(), url);
                console.debug("%crequest:\t", "background-color:#aff;", {
                    type: "post",
                    url: url,
                    data: data
                });
                console.debug("%cresponse:\t", "background-color:#ffa;", val);
                console.groupEnd();

                wx.showModal({
                    title: '提示',
                    content: '网络异常，请稍候重试！',                    
                    success(res) {
                        if (res.confirm) {
                            post(url, data, showloading, msgTitle);
                        } else if(res.cancel){
                            // wx.navigateBack({
                            // });
                        }
                    }
                });
            },
            success: function(res) {
                console.group("%c【%s】- 成功请求服务端：%s\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
                    "background-color:#afa;font-weight:800;", new Date().toLocaleString(), url);
                console.debug("%crequest:\t", "background-color:#aff;", {
                    type: "post",
                    url: url,
                    data: data
                });
                console.debug("%cresponse:\t", "background-color:#ffa;", res);
                console.groupEnd();
                if (res.data.message == 'timeOut') {
                    app.globalData.currUserInfo.userId = -1;
                }
              if (res.data.success==true) {              
                    if (msgTitle != null && msgTitle != ""){
                        app.globalData.showLoadingMap["toast_" + showLoadingId] = new Date();
                        //
                        wx.showToast({
                            title: msgTitle,
                            icon: 'succes',
                            duration: 1000,
                            mask: true
                        });
                        setTimeout(function(){
                            delete app.globalData.showLoadingMap["toast_" + showLoadingId];
                        }, 1000);
                    }
                    resolve(res);                                        
                } else { //返回错误提示信息
                console.log("错误的url", url)
                if (res.data.msg == 'timeOut') {
                  reject('登录超时，请重新登录');
                } else if (res.data.msg == 'relogin') {
                  reject('登录超时，请重新登录');
                  setTimeout(function () {
                   
                  }, 2000);
                } else {
                  reject(res.data.message);
                }
                  
                }

            }
        })

    });
    return promise;
}


function uploadFile(url, file, data, showloading, msgTitle, complete_callBack) {
    const app = getApp();
    var promise = new Promise((resolve, reject) => {
        data = hexMD5(app, data);
        if (showloading == null) {
            showloading = false;
        }
        var showLoadingId = app.globalData.accumulator++ % 10000;
        app.globalData.showLoadingMap["loading_" + showLoadingId] = new Date();
        setTimeout(function () {
            if (showloading) {
                wx.showLoading({
                    title: '',
                    icon: 'none',
                    mask: true
                });
            }
        }, 1);
        //
        wx.uploadFile({
            url: url,
            filePath: file,
            name: 'file',
            formData: data,
            complete: function (res) {
                //
                showloading = false;
                delete app.globalData.showLoadingMap["loading_" + showLoadingId];
                if (Object.keys(app.globalData.showLoadingMap).length == 0) {
                    setTimeout(function () {
                        if (Object.keys(app.globalData.showLoadingMap).length == 0) {
                            wx.hideLoading();
                        }
                    }, 300);
                }
                if (complete_callBack) {
                    complete_callBack();
                }
            },
            fail: function (val) {
                //
                console.group("%c【%s】- 上传文件到服务器失败：%s\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
                    "background-color:#faa;font-weight:800;", new Date().toLocaleString(), url);
                console.debug("%crequest:\t", "background-color:#aff;", {
                    type: "post",
                    url: url,
                    data: data
                });
                console.debug("%cresponse:\t", "background-color:#ffa;", val);
                console.groupEnd();

                // wx.showModal({
                //     title: '提示',
                //     content: '当前网络开小差了，请再重试一次！',
                //     success(res) {
                //         if (res.confirm) {
                //             post(url, data, showloading, msgTitle);
                //         } else if (res.cancel) {
                //             // wx.navigateBack({                                
                //             // });
                //         }
                //     }
                // });
            },
            success: function (res) {
                //                
                console.group("%c【%s】- 上传文件到服务器成功：%s\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
                    "background-color:#afa;font-weight:800;", new Date().toLocaleString(), url);
                console.debug("%crequest:\t", "background-color:#aff;", {
                    type: "post",
                    url: url,
                    data: data
                });
                var resultData = JSON.parse(res.data);
                res.data = resultData;
                console.debug("%cresponse:\t", "background-color:#ffa;", res);
                console.groupEnd();
                if (resultData.message == 'timeOut') {
                    app.globalData.currUserInfo.userId = -1;
                }
                if (resultData.success) {
                    if (msgTitle != null && msgTitle != "") {
                        app.globalData.showLoadingMap["toast_" + showLoadingId] = new Date();
                        //
                        wx.showToast({
                            title: msgTitle,
                            icon: 'succes',
                            duration: 1000,
                            mask: true
                        });
                        setTimeout(function () {
                            delete app.globalData.showLoadingMap["toast_" + showLoadingId];
                        }, 1000);
                    }
                    resolve(res);
                } else { //返回错误提示信息
                    console.log("错误的url", url)
                    if (resultData.message == 'timeOut') {
                        reject('登录超时，请重新登录');
                    } else if (resultData.message == 'relogin') {
                        reject('登录超时，请重新登录');
                        setTimeout(function () {
                            wx.navigateTo({
                                url: '/pages/my/login/login?relogin=true',
                            });
                        }, 2000);
                    } else {
                        reject(resultData.message);
                    }
                }

            }
        });
    });
    return promise;
}

function hexMD5(app,data) {    
    var nonce_str = Math.random().toString(36).substr(2, 15);
    var timestamp = Date.parse(new Date());
    var secret = MD5.hexMD5("productId=" + app.globalData.productId + "&token=" + app.globalData.currUserInfo.token + "&nonce_str=" + nonce_str + "&timestamp=" + timestamp);
    data.nonce_str = nonce_str;
    data.timestamp = timestamp;
    data.secret = secret;
    data.userId = app.globalData.currUserInfo.userId;//所有请求都加上userId，为了获取token
    return data;
}


function GET(url, data, showloading, msgTitle, complete_callBack) {
  const app = getApp();
  var promise = new Promise((resolve, reject) => {
    setTimeout(function () {
      if (showloading) {
        wx.showLoading({
          title: '',
          icon: 'none',
          mask: true
        });
      }
    }, 1);
    wx.request({
      url: url,
      data: data,
      method: "GET",
      header: {
        'content-type': 'application/json'
      },
      complete: function (res) {
        showloading = false;
        if (complete_callBack) {
          complete_callBack();
        }
      },
      fail: function (val) {
        console.group("%c【%s】- 失败请求服务端：%s\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
          "background-color:#faa;font-weight:800;", new Date().toLocaleString(), url);
        console.debug("%crequest:\t", "background-color:#aff;", {
          type: "post",
          url: url,
          data: data
        });
        console.debug("%cresponse:\t", "background-color:#ffa;", val);
        console.groupEnd();

        wx.showModal({
          title: '提示',
          content: '网络异常，请稍候重试！',
          success(res) {
            if (res.confirm) {
              post(url, data, showloading, msgTitle);
            } else if (res.cancel) {
              // wx.navigateBack({
              // });
            }
          }
        });
      },
      success: function (res) {
        console.group("%c【%s】- 成功请求服务端：%s\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
          "background-color:#afa;font-weight:800;", new Date().toLocaleString(), url);
        console.debug("%crequest:\t", "background-color:#aff;", {
          type: "post",
          url: url,
          data: data
        });
        console.debug("%cresponse:\t", "background-color:#ffa;", res);
        console.groupEnd();
        if (res.data.message == 'timeOut') {
          app.globalData.currUserInfo.userId = -1;
        }
        if (res.data.success == true) {        
          if (msgTitle != null && msgTitle != "") {
            app.globalData.showLoadingMap["toast_" + showLoadingId] = new Date();
            //
            wx.showToast({
              title: msgTitle,
              icon: 'succes',
              duration: 1000,
              mask: true
            });
            setTimeout(function () {
              delete app.globalData.showLoadingMap["toast_" + showLoadingId];
            }, 1000);
          }
          resolve(res);
        } else { //返回错误提示信息
          console.log("错误的url", url)
          if (res.data.msg == 'timeOut') {
            reject('登录超时，请重新登录');
          } else if (res.data.msg == 'relogin') {
            reject('登录超时，请重新登录');
            setTimeout(function () {

            }, 2000);
          } else {
            reject(res.data.message);
          }

        }

      }
    })

  });
  return promise;
}
function POSTFORM(url, data, showloading, msgTitle, complete_callBack) {
  const app = getApp();
  var promise = new Promise((resolve, reject) => {
    setTimeout(function () {
      if (showloading) {
        wx.showLoading({
          title: '',
          icon: 'none',
          mask: true
        });
      }
    }, 1);
    wx.request({
      url: url,
      data: data,
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded '
      },
      complete: function (res) {
        showloading = false;
        if (complete_callBack) {
          complete_callBack();
        }
      },
      fail: function (val) {
        console.group("%c【%s】- 失败请求服务端：%s\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
          "background-color:#faa;font-weight:800;", new Date().toLocaleString(), url);
        console.debug("%crequest:\t", "background-color:#aff;", {
          type: "post",
          url: url,
          data: data
        });
        console.debug("%cresponse:\t", "background-color:#ffa;", val);
        console.groupEnd();

        wx.showModal({
          title: '提示',
          content: '网络异常，请稍候重试！',
          success(res) {
            if (res.confirm) {
              post(url, data, showloading, msgTitle);
            } else if (res.cancel) {
              // wx.navigateBack({
              // });
            }
          }
        });
      },
      success: function (res) {
        console.group("%c【%s】- 成功请求服务端：%s\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
          "background-color:#afa;font-weight:800;", new Date().toLocaleString(), url);
        console.debug("%crequest:\t", "background-color:#aff;", {
          type: "post",
          url: url,
          data: data
        });
        console.debug("%cresponse:\t", "background-color:#ffa;", res);
        console.groupEnd();
        if (res.data.message == 'timeOut') {
          app.globalData.currUserInfo.userId = -1;
        }
        if (res.data.success == true) {        
          if (msgTitle != null && msgTitle != "") {
            app.globalData.showLoadingMap["toast_" + showLoadingId] = new Date();
            //
            wx.showToast({
              title: msgTitle,
              icon: 'succes',
              duration: 1000,
              mask: true
            });
            setTimeout(function () {
              delete app.globalData.showLoadingMap["toast_" + showLoadingId];
            }, 1000);
          }
          resolve(res);
        } else { //返回错误提示信息
          console.log("错误的url", url)
          if (res.data.msg == 'timeOut') {
            reject('登录超时，请重新登录');
          } else if (res.data.msg == 'relogin') {
            reject('登录超时，请重新登录');
            setTimeout(function () {

            }, 2000);
          } else {
            reject(res.data.message);
          }

        }

      }
    })

  });
  return promise;
}


module.exports = {
    POSTJSON: POSTJSON,
    uploadFile: uploadFile,
    GET: GET,
    POSTFORM: POSTFORM,
}